package com.josework.springhelloworld.exception;

import com.josework.springhelloworld.base.BaseResponse;
import com.josework.springhelloworld.controller.BaseController;
import com.josework.springhelloworld.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends BaseController {

    /**
     * 异常处理
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResponse errorHandler(Exception e) {
        log.error("exception:{}", e);
        return fail("Error 咯！");
    }


    /**
     * 参数校验
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public BaseResponse methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String defaultMessage = fieldErrors.stream()
                .map(cv -> cv == null ? "null" : cv.getField() + ":" + cv.getDefaultMessage())
                .collect(Collectors.joining(", "));
        log.error("validation Bean property result:{}", defaultMessage);
        return fail(defaultMessage);
    }

    /**
     * dealTerm异常处理
     */
    @ResponseBody
    @ExceptionHandler(value = UserException.class)
    public BaseResponse exception(UserException e) {
        return new BaseResponse(e.getCode(), e.getMsg());
    }


}